<?php
/**
 * @author Erlend Strømsvik - Ny Media AS
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package moodle multiauth
 *
 * Authentication Plugin: Feide Authentication
 *
 * Authentication using SAML2 with SimpleSAMLphp. 
 *
 * Based on plugins made by Sergio Gómez (moodle_ssp) and Martin Dougiamas (Shibboleth).
 *
 * 2008-10  Created
**/

if (!defined('MOODLE_INTERNAL')) {
    die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
}

require_once($CFG->libdir.'/authlib.php');

/**
 * SimpleSAML authentication plugin.
**/
class auth_plugin_feide extends auth_plugin_base {
    
    /**
    * Constructor.
    */
    function auth_plugin_feide() {
        $this->authtype = 'feide';
        $this->config = get_config('auth/feide');
    }
    
    /**
    * Returns true if the username and password work and false if they are
    * wrong or don't exist.
    *
    * @param string $username The username (with system magic quotes)
    * @param string $password The password (with system magic quotes)
    * @return bool Authentication success or failure.
    */
    function user_login($username, $password) {
        // if true, user_login was initiated by feide/index.php
        if($GLOBALS['feide_login']) {
            unset($GLOBALS['feide_login']);
            return TRUE;
        }
        
        return FALSE;
    }
    
    
    /**
    * Returns the user information for 'external' users. In this case the
    * attributes provided by feide
    *
    * @return array $result Associative array of user data
    */
    function get_userinfo($username) {
        if($GLOBALS['feide_login_attributes']) {
            $attributemap = $this->get_attributes();
            $result = array();
            
            foreach ($attributemap as $key => $value) {
                if($attribute = $GLOBALS['feide_login_attributes'][$value][0]) {
                    $result[$key] = $attribute;
                } else {
                    $result[$key] = '';
                }
            }
            
            unset($GLOBALS['feide_login_attributes']);
            return $result;
        }
        
        return FALSE;
    }
    
    /*
    * Returns array containg attribute mappings between Moodle and feide.
    */
    function get_attributes() {
        $configarray = (array) $this->config;
        
        $fields = array("firstname", "lastname", "email", "phone1", "phone2",
            "department", "address", "city", "country", "description",
            "idnumber", "lang", "guid");
        
        $moodleattributes = array();
        foreach ($fields as $field) {
            if (isset($configarray["field_map_$field"])) {
                $moodleattributes[$field] = $configarray["field_map_$field"];
            }
        }
        $moodleattributes['username'] = $configarray["user_attribute"];
        
        return $moodleattributes;
    }
    
    /**
    * Returns true if this authentication plugin is 'internal'.
    *
    * @return bool
    */
    function is_internal() {
        return false;
    }
    
    /**
    * Returns true if this authentication plugin can change the user's
    * password.
    *
    * @return bool
    */
    function can_change_password() {
        return false;
    }
    
    function loginpage_hook() {
        // Prevent username from being shown on login page after logout
        $GLOBALS['CFG']->nolastloggedin = true;
        
        return;
    }

    function logoutpage_hook() {
        if($this->config->dologout) {
            set_moodle_cookie('nobody');
            require_logout();
            redirect($GLOBALS['CFG']->wwwroot.'/auth/feide/index.php?logout=1');
        }
    }
    
    /**
    * Prints a form for configuring this authentication plugin.
    *
    * This function is called from admin/auth.php, and outputs a full page with
    * a form for configuring this plugin.
    *
    * @param array $page An object containing all the data for this page.
    */

    function config_form($config, $err, $user_fields) {
        include "config.html";
    }

    
    /**
    * Processes and stores configuration data for this authentication plugin.
    *
    *
    * @param object $config Configuration object
    */
    function process_config($config) {
        // set to defaults if undefined
        if (!isset ($config->entityid)) {
            $config->entityid = '';
        }
        if (!isset ($config->dologout)) {
            $config->dologout = '';
        }
        if (!isset ($config->notshowusername)) {
            $config->notshowusername = '';
        }
        
        // save settings
        set_config('entityid',        $config->entityid,        'auth/feide');
        set_config('dologout',        $config->dologout,        'auth/feide');
        set_config('notshowusername', $config->notshowusername, 'auth/feide');
        
        return true;
    }
    
    /**
    * Cleans and returns first of potential many values (multi-valued attributes)
    *
    * @param string $string Possibly multi-valued attribute from feide
    */
    function get_first_string($string) {
        $list = split( ';', $string);
        $clean_string = trim($list[0]);
        
        return $clean_string;
    }
}

?>
